package com.zc.blog.controller;

import com.zc.blog.model.Article;
import com.zc.blog.model.Category;
import com.zc.blog.service.IArticleService;
import com.zc.blog.service.ICategoryService;
import com.zc.blog.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;


@Controller
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private IArticleService articleService;

    @Autowired
    private ICategoryService categoryService;

    @Value("${pageSize}")
    private int pageSize;

    /**
     * 根据类别Id获取文章
     * @param categoryId 类别id
     */
    @RequestMapping("/{categoryId}")
    public String getCategoryList(@PathVariable("categoryId") Integer categoryId, @RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "query",required = false) String query, Model model) {
        Category category = categoryService.findById(categoryId); //获取当前类别
        List<Article> categoryArticlesList = articleService.listCategoryArticles(page,pageSize,query,categoryId); //根据类别获取文章
        int total = articleService.getCategoryArticlesTotal(query,categoryId);// 获取符合查询条件的文章总数
        String pageCode= PageUtil.genPagation("/category/"+categoryId, total, page, pageSize,query); // 生成分页链接

        model.addAttribute("category", category);    //当前类别
        model.addAttribute("categoryArticlesList", categoryArticlesList);  //类别文章列表
        model.addAttribute("pageCode", pageCode);  //分页链接
        model.addAttribute("query", query);        //查询参数
        return "blog/articleCategory";
    }

}
